<?php
import("com.yamvc.render.IEngine");
import("com.yamvc.render.TemplateNotRegisteredException");
import("com.miho.exceptions.NoSuchDirectoryException");
import("com.miho.exceptions.NoSuchFileException");
import("com.miho.io.File");
import("com.PHPTemplater.Template");
class Engine implements IEngine {
	private $_basePath="./";
	/**
	 * Enter description here...
	 *
	 * @var ITemplate
	 */
	private $_rootTemplate;
	private $_templates=array();
	
	public function setBasePath($path){
		if (!is_dir($path)){
			throw new NoSuchDirectoryException($path);
		}
		$this->_basePath = $path;
	}
	public function createTemplate($name,$var=""){
		$templatePath = $this->_basePath."/".$name.".tpl.php";
		if(!File::exists($templatePath)){
			throw new NoSuchFileException($templatePath);
		}
		$this->_templates[$name] = new Template($templatePath,$var); 
		return $this->_templates[$name]; 
	}
	
	public function createRootTemplate($name){
		$this->_rootTemplate = $this->createTemplate($name);
		foreach ($this->_templates as $name=>$template){
			//var_dump($name);
			$template->setParent($this->_rootTemplate);
		}
		return $this->_rootTemplate;
	}
	
	public function render(){
		$scripts="";
		$scriptPath = Application::getAppInstance()->getScriptPath();
		foreach ($this->_scripts as $scriptName) {
			$scripts .='<script type="text/javascript" src="'.$scriptPath.$scriptName.'.js" ></script>';
		}
		
		$styles="";
		$stylesPath = Application::getAppInstance()->getScriptPath();
		foreach ($this->_styles as $styleName) {
			$styles .='<style type="text/css" src="'.$stylesPath.$styleName.'.css" />';
		}
		$this->_rootTemplate->putVariable("headScripts",$scripts);
		$this->_rootTemplate->putVariable("headStyles",$styles);
		
		echo $this->_rootTemplate->render();
	}
	
	/**
	 * Enter description here...
	 *
	 * @param string
	 * @return ITemplate
	 */
	public function getTemplate($name){
		if (!isset($this->_templates[$name])){
			throw new TemplateNotRegisteredException($name);
		}
		return $this->_templates[$name];
	}
	
	/**
	 * Enter description here...
	 *
	 * @return ITemplate
	 */
	public function getRootTemplate(){
		return $this->_rootTemplate;
	}
	
	private $_scripts=array();
	public function addScript($scriptName){
		array_push($this->_scripts,$scriptName);
	}
	private $_styles=array();
	public function addStyle($styleName){
		array_push($this->_styles,$styleName);
	}
	
}

?>


